//
//  WmcMotionManager.swift
//  YPWatermarkCamera
//
//  Created by 赵新 on 2022/3/8.
//

import CoreMotion
import Foundation
import UIKit
import YPBedrock

class WmcMotionManager {
    // Public

    /// 单例实例化
    public static let shared: WmcMotionManager = {
        let manager = WmcMotionManager()
        return manager
    }()

    /// 当前设备方向
    public let orientation: BehaviorRelay<UIDeviceOrientation> = .init(value: .portrait)

    // Internal

    /// 设备重力感应
    let motionManager = CMMotionManager()

    /// 频率
    var frequency = 90

    /// 设置重力感应
    func config() {}

    func start() {
        guard motionManager.isDeviceMotionAvailable else { return }
        var count = 0
        motionManager.startDeviceMotionUpdates(to: .main) { [weak self] motion, _ in
            guard let weakSelf = self else { return }
            guard count >= weakSelf.frequency else // 防止频率
            {
                count += 1
                return
            }
            // 屏幕旋转角度
            if let gravity_x = motion?.gravity.x,
               let gravity_y = motion?.gravity.y
            {
                let screen_angle: CGFloat = Double.pi / 2.0 - atan2(gravity_y, gravity_x)
                let screenAngle = screen_angle.yp.radianToAngle.yp.int
                calculateDirection(screenAngle)
            }

            count = 0
        }
        func calculateDirection(_ angle: Int) {
            let portraitStart = 180 + 55
            let landscapeRightStart = 180 - 55
            let portraitUpsideDownStart = 15
            let landscapeLeftStart = -15
            /**
                              180
                        270        设备        90
                               0
             */
            // 判断角度
            if landscapeRightStart ..< portraitStart ~= angle,
               orientation.value != .portrait
            {
                orientation.accept(.portrait)
                //                log("设备正向")
            } else if portraitUpsideDownStart ..< landscapeRightStart ~= angle,
                      orientation.value != .landscapeRight
            {
                orientation.accept(.landscapeRight)
                //                log("设备向右")
            } else if (landscapeLeftStart ..< 0 ~= angle ||
                0 ..< portraitUpsideDownStart ~= angle),
                orientation.value != .portraitUpsideDown
            {
                orientation.accept(.portraitUpsideDown)
                //                log("设备向下")
            } else if (-90 ..< landscapeLeftStart ~= angle ||
                portraitStart ..< 270 ~= angle),
                orientation.value != .landscapeLeft
            {
                orientation.accept(.landscapeLeft)
                //                log("设备向左")
            }
        }
    }

    func stop() {
        motionManager.stopDeviceMotionUpdates()
    }

    // Fileprivate

    /// 日志系统
    fileprivate func log(_ log: String) {
        WmcLogManager.DebugLog(type: .motionManager, log: log)
    }
}
